import { Form } from '@alifd/next';
import React, { useEffect, useState } from 'react';
import { TitleGrid } from './stores/OrderChangeStore';
import SurchargesFieldsGrid from '../SurchargesFieldsGrid';
import { t } from '@lingui/macro';
import { useStore } from '@/hooks';
import { observer } from 'mobx-react-lite';

const OrderSurchargeList = (props) => {
  const { order, index, type, form } = props;
  const { orderChangeStore: store } = useStore();
  const [surcharge, setSurcharge] = useState({});
  const [merchantSur, setMerchantSur] = useState({});
  const title = type === 'merchant' ? '商户' : '承运商';

  useEffect(() => {
    (async () => {
      const merchantId = order?.merchant;
      if (merchantId) {
        const { merchantSurcharges } = await store.getMerchantInfo(merchantId);
        setMerchantSur(merchantSurcharges);
      }
    })();
  }, [order]);

  useEffect(() => {
    const orderSur = order?.ccOrder?.surcharges[index];
    const merchantKeys = Object.keys(merchantSur) || [];
    const exclude = type === 'merchant';
    const data = filterSurcharge(orderSur, merchantKeys, exclude);
    setSurcharge(data);
  }, [order, index, type, merchantSur]);

  function filterSurcharge(allSur, excludeKey, exclude) {
    let res = {};
    const allKeys = Object.keys(allSur);
    if (exclude) {
      res = allKeys.reduce((result, key) => {
        if (excludeKey.includes(key)) {
          result[key] = allSur[key];
        }
        return result;
      }, res);
    } else {
      res = allKeys.reduce((result, key) => {
        if (!excludeKey.includes(key)) {
          result[key] = allSur[key];
        }
        return result;
      }, res);
    }
    return res;
  }

  return (
    <Form isPreview={Boolean(true)} style={{ width: '100%' }}>
      <TitleGrid title={t`订单原${title}附加费参考列表`} />
      <SurchargesFieldsGrid
        dataSource={surcharge || {}}
      />
    </Form>
  );
};

export default observer(OrderSurchargeList);
